# coding=utf-8
import urllib2
import urllib
import sys
import json
import time
import argparse
import random
import datetime

reload(sys)
sys.setdefaultencoding("utf-8")
args = None

gate_url_qa = "http://sdk-tb-gate-service:8080/gate"
gate_url_mini = "http://wangcai-mini.xiaoduoai.com/sdk-tb-gate"

no_auth_args = {"namespace":"mini-app"}


def query_jms(shop_list, interval=0.02):
    method = "taobao.jushita.jms.topics.get"
    query_args = {}
    result = []
    for i, shop in enumerate(shop_list):
        query_args["nick"] = shop
        reply = j_http_common(shop, method, query_args, args.auth)
        if reply["code"] != 0 or reply["error"] != "":
            print("query {} jms failed {}".format(shop, reply))
            result.append((shop, False, reply["error"]))
        else:
            jms_data = json.loads(reply["rsp_data"])

            if jms_data.has_key("result_message"):
                result.append((shop, False, "{}:{}".format(jms_data["result_code"], jms_data["result_message"])))
            elif jms_data["results"].has_key("string"):
                result.append((shop, len(jms_data["results"]["string"]) > 0))
            else:
                result.append((shop, False))
        print("i={}, shop={}, result={}".format(i, shop, result[-1]))
        time.sleep(interval)
    return result


def query_jdp(shop_list, interval=0.02):
    pageSize = 5000
    method = "taobao.jushita.jdp.users.get"
    jdp_users = {}
    page = 1
    while True:
        query_args = {
            "page_size": pageSize,
            "page_no": page
        }
        reply = j_http_common("", method, query_args, args.auth)
        if reply["code"] != 0 or reply["error"] != "":
            print("query jdp shops failed:{}".format(reply))
            return
        rds_data = json.loads(reply["rsp_data"])
        jdp_users.update({user["user_nick"]:user for user in rds_data["users"]["jdp_user"]})
        if len(jdp_users) == rds_data["total_results"]:
            break
        page += 1
        time.sleep(interval)
    
    result = []
    for i, shop in enumerate(shop_list):
        skey = shop.decode('utf-8')
        if jdp_users.has_key(skey):
            result.append((shop, True, jdp_users[skey]["rds_name"], jdp_users[skey]["status"]))
        else:
            result.append((shop, False, "", ""))
        print("i={}, shop={}, result={}".format(i, shop, result[-1]))
    return result


def delete_jms(shop_list, interval=0.02):
    method = "taobao.jushita.jms.user.delete"
    query_args = {}
    result = []
    for i, shop in enumerate(shop_list):
        query_args["user_nick"] = shop
        reply = j_http_common(shop, method, query_args, args.auth)
        if reply["code"] != 0 or reply["error"] != "":
            print("delete {} jms failed:{}".format(shop, reply))
            result.append((shop, False, reply["error"]))
        else:
            data = json.loads(reply["rsp_data"])
            if data.has_key("result_message"):
                result.append((shop, False, "{}:{}".format(jms_data["result_code"], jms_data["result_message"])))
            else:
                result.append((shop, True, data))

        print("i={}, shop={}, result={}".format(i, shop, result[-1]))
        time.sleep(interval)
    return result

def delete_jdp(shop_list, interval=0.02):
    query_args = {}
    method = "taobao.jushita.jdp.user.delete"
    result = []
    for i, shop in enumerate(shop_list):
        query_args["nick"] = shop
        reply = j_http_common(shop, method, query_args, args.auth)
        if reply["code"] != 0 or reply["error"] != "":
            print("delete {} jdp failed:{}".format(shop, reply))
            result = append((shop, False, reply["error"]))
        else:
            data = json.loads(reply["rsp_data"])
            if data.has_key("result_message"):
                result.append((shop, False, "{}:{}".format(jms_data["result_code"], jms_data["result_message"])))
            else:
                result.append((shop, True, data))

        time.sleep(interval)
        print("i={}, shop={}, result={}".format(i, shop, result[-1]))
    return result

def add_jdp(shop_list, interval=0.02):
    rds_name = args.rds
    if rds_name is None:
        print("error: add jdp need rds")
        return
    method = "taobao.jushita.jdp.user.add"
    print("add jdp rds={}".format(rds_name))
    query_args = {"rds_name":rds_name}
    result = []
    for i, shop in enumerate(shop_list):
        reply = j_http_common(shop, method, query_args, auth=True)
        if reply["code"] != 0 or reply["error"] != "":
            print("add {} jdp rds {} failed:{}".format(shop, rds_name, reply))
            result.append((shop, False, rds_name, reply["error"]))
        else:
            data = json.loads(reply["rsp_data"])
            if data.has_key("result_message"):
                result.append((shop, False, rds_name, "{}:{}".format(jms_data["result_code"], jms_data["result_message"])))
            else:
                result.append((shop, True, rds_name, data))

        print("i={}, shop={}, result={}".format(i, shop, result[-1]))
        time.sleep(interval)
    return result

def add_jms(shop_list, interval=0.02):
    method = "taobao.jushita.jms.user.add"
    query_args = {}
    result = []
    for i, shop in enumerate(shop_list):
        reply = j_http_common(shop, method, query_args, auth=True)
        if reply["code"] != 0 or reply["error"] != "":
            print("add {} jms failed:{}".format(shop, reply))
            result.append((shop, False, reply["error"]))
        else:
            data = json.loads(reply["rsp_data"])
            if data.has_key("result_message"):
                result.append((shop, False, "{}:{}".format(jms_data["result_code"], jms_data["result_message"])))
            else:
                result.append((shop, True, data))

        print("i={}, shop={}, result={}".format(i, shop, result[-1]))
        time.sleep(interval)
    return result

def query_chat_count(shop_list, interval=1):
    now_tm = datetime.datetime.now()
    start_day = (now_tm - datetime.timedelta(days=15)).strftime("%Y-%m-%d")
    end_day = now_tm.strftime("%Y-%m-%d")
    chat_result = []
    url ="http://10.22.116.138:8090/opapi/proxy/opmanagement/admin/query_chat_count"
    print("start_day={}, end_day={}".format(start_day, end_day))
    for i, shop in enumerate(shop_list):
        # 查询两周没有聊过天的玩家
        postdata = {"plat_user_id" : shop, "start_day" : start_day, "end_day" : end_day}
        postdata = json.dumps(postdata)
        request = urllib2.Request(url, postdata)
        request.add_header('Content-Type','application/json')
        request.add_header('transto','json')
        reply = {}
        count = -1
        if args.test:
            reply = {"success":True, "data":{"code":0, "data":{"count":10}}}
        else:
            response = urllib2.urlopen(request, timeout=4)
            reply = json.loads(response.read())
        if reply["success"] and reply["data"]["code"] == 0:
            count = reply["data"]["data"]["count"]
            chat_result.append((shop, True, str(count)))
        else:
            print("query chat count failed, shop={}, reply={}".format(shop, reply))
            chat_result.append((shop, False, 0))
        print("i={}, shop={}, result={}".format(i, shop, chat_result[-1])) 
        time.sleep(interval)
    return chat_result


def delete_token(shop_list, interval=0.02):
    url = "http://10.22.116.138:8090/api/auth"
    token_result = []
    for i, shop in enumerate(shop_list):
        param = {"user_nick":shop, "access_token":"123"}
        urlget = url + "?" + urllib.urlencode(param)
        reply = {}
        one_result = ()
        if args.test:
            reply = {"success":True, "data":{"code":random.randint(0, 5), "message":"test"}}
        else:
            request = urllib2.Request(urlget)
            response = urllib2.urlopen(request, timeout=4)
            reply = json.loads(response.read())
        if reply["success"] == True:
            one_result = (shop, "True", reply["data"]["message"])
        else:
            one_result = (shop, "False", "err_code:{} err_msg:{}".format(reply["error_code"], reply["error_message"]))
        token_result.append(one_result)
        print("i={}, shop={}, result={}".format(i, shop, token_result[-1]))
        time.sleep(interval)
    return token_result


def delete_all(shop_list):
    result = []

    for i, shop in enumerate(shop_list):
        print("--------delete start:{}---------".format(i+1))
        one_result = []
        # 查询聊天
        chat_res = query_chat_count(shop, 0)[0]
        one_result.extend(["(chat)"+item for item in chat_res])
        if chat_res[1] == "0": 
            # 删除jms
            jms_res = delete_jms([shop], 0)[0]
            one_result.extend(["(jms)"+item for item in jms_res[1:]])

            # 删除jdp
            jdp_res = delete_jdp([shop], 0)[0]
            one_result.extend(["(jdp)"+item for item in jdp_res[1:]])

            # 删除token
            token_res = delete_token([shop], 0)[0]
            one_result.extend(["(token)"+item for item in token_res[1:]])

        result.append(one_result)
        time.sleep(1)

    return result

def not_support(shop_list):
    print('not support "{} {}"'.format(args.operate, args.jtype))


def j_http_common(shop_name, method, query_args, auth=False): 
    if not auth:
        query_args.update(no_auth_args)
    data = {
        "usernick":shop_name, 
        "method": method,
        "args": query_args,
        "uri": "http://gw.api.taobao.com/router/rest",
        "withuserauth": auth,
        "external": False
    }
    reply = {}
    postdata = json.dumps(data)
    if args.test:
        reply = {"code":random.randint(0, 5), "error":"", "rsp_data":"", "access_token":"", "client_id":""}
    else:
        url = gate_url_qa
        if args.mini:
            url = gate_url_mini
        request = urllib2.Request(url, postdata)
        response = urllib2.urlopen(request, timeout=4)
        reply = json.loads(response.read())
    return reply


def get_shop_list(shop_file):
    with open(shop_file, "r") as fp:
        shop_list = []
        for shop in fp:
            shop_list.append(shop.strip())
        return shop_list

if __name__ == "__main__":
    parser = argparse.ArgumentParser() 
    parser.add_argument(dest="operate", help="query or delete or add", choices=("add", "query", "delete"), type=str)
    parser.add_argument(dest="jtype", help="chat or jms or jdp or token, all", 
                choices=("chat", "all", "jms", "jdp", "token"), type=str)
    parser.add_argument(dest="shop_file", help="shop list file", type=str)
    parser.add_argument("--rds", dest="rds", help="needed when add jdp", type=str)
    parser.add_argument("--test", "-t", dest="test", action="store_true", help="use test, not request http") # 当使用测试时，不会真正发起http请求
    parser.add_argument("--auth", "-a", dest="auth", action="store_true", help="jdp or jms is need auth") # 当使用测试时，不会真正发起http请求
    parser.add_argument("--mini", "-m", dest="mini", action="store_true", help="use mini env") # 当使用测试时，不会真正发起http请求
    args = parser.parse_args()
    shop_list = get_shop_list(args.shop_file)
    jtype = args.jtype
    op = args.operate

    handlers = {
        "all":{"query":not_support, "delete":delete_all, "add":not_support},
        "chat":{"query":query_chat_count, "delete":not_support, "add":not_support},
        "jms":{"query":query_jms, "delete":delete_jms, "add":add_jms}, 
        "jdp":{"query":query_jdp, "delete":delete_jdp, "add":add_jdp},
        "token":{"query":not_support, "delete":delete_token, "add":not_support}
        }
    handler = handlers[jtype][op]

    result = handler(shop_list)
    if result is not None and len(result) > 0:
        with open("{}.txt".format(handler.func_name), "w+") as fp:
            fp.writelines(["{}\n".format(",".join([str(item) for item in line])) for line in result])


